package org.makcro.sms.services.chat.web.server.services;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.dozer.Mapper;
import org.makcro.sms.services.chat.model.BulkMessage;
import org.makcro.sms.services.chat.web.client.services.message.BulkService;
import org.makcro.sms.services.chat.web.shared.dto.BulkMessageDto;

import com.extjs.gxt.ui.client.data.BasePagingLoadResult;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import com.extjs.gxt.ui.client.data.PagingLoadResult;

public class BulkServiceFacade implements BulkService {

	/**
	 * Logger instance
	 */
	private Logger													logger	= Logger.getLogger( BulkServiceFacade.class );

	private org.makcro.sms.services.chat.base.business.BulkService	bulkService;

	private Mapper														mapper;
	
	@Override
	public int sendBulk(String messageText, String signature, List<String> receivers) {
		int messagesSent = bulkService.sendBulk( messageText, signature, receivers );

		logger.info( MessageFormat.format( "[{0}] bulk messsages forwarded to bulk service", messagesSent ) );
		return messagesSent;
	}

	public void setBulkService(org.makcro.sms.services.chat.base.business.BulkService bulkService) {
		this.bulkService = bulkService;
	}

	@Override
	public PagingLoadResult<BulkMessageDto> search(PagingLoadConfig loadConfig) {
		// extract paging params
		int offset = loadConfig.getOffset();
		int limit = loadConfig.getLimit();

		// load paging data
		List<BulkMessage> agentsMessages = this.bulkService.search( new int[] { offset, limit } );
		Long count = this.bulkService.getSearchCount();

		// convert data
		// convert to dto
		List<BulkMessageDto> dtoMessages = new ArrayList<BulkMessageDto>( agentsMessages.size() );
		for (BulkMessage bulkMessage : agentsMessages) {
			BulkMessageDto bulkMessageDto = this.mapper.map( bulkMessage, BulkMessageDto.class );
			dtoMessages.add( bulkMessageDto );
		}
		PagingLoadResult<BulkMessageDto> loadResult = new BasePagingLoadResult<BulkMessageDto>( dtoMessages, offset, (int)Math.min( Integer.MAX_VALUE, count ) );
		return loadResult;
	}
	
	public void setMapper(Mapper mapper) {
		this.mapper = mapper;
	}
}
